import React, { useEffect, useState, useRef } from 'react';
import { Modal, message, Spin, Cascader } from 'antd';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import services from '@/services/files';

const { fetchPositions, fetchScores, fetchFileTree } = services.PositionScore;

const PositionPage: React.FC = () => {
  const [tableData, setTableData] = useState<any[]>([]);
  const [tableColumns, setTableColumns] = useState<ProColumns<any>[]>([]);
  const [tableLoading, setTableLoading] = useState(false);

  const [scoreData, setScoreData] = useState<any[]>([]);
  const [scoreColumns, setScoreColumns] = useState<ProColumns<any>[]>([]);
  const [scoreVisible, setScoreVisible] = useState(false);
  const [scoreLoading, setScoreLoading] = useState(false);

  const [selectedFile, setSelectedFile] = useState<any[]>([]);
  const [ready, setReady] = useState(false);
  const actionRef = useRef<ActionType>();
  const [fileTree, setFileTree] = useState<any[]>([]);

  // ====== 本地存储 key ======
  const STORAGE_KEY = 'position_page_selected_file';

  // 点击职位代码 -> 弹窗 + 加载成绩
  const openScoreDialog = async (positionCode: string) => {
    setScoreVisible(true);
    setScoreLoading(true);
    try {
      const [province, date, type, city] = selectedFile;
      const res = await fetchScores({
        province,
        city,
        date,
        positionCode,
      });
      setScoreData(res.data || []);
      const cols = (res.fractionNameKeyMap || []).map((col: any) => ({
        title: col.name || col,
        dataIndex: col.key || col,
        ...col,
      }));
      setScoreColumns(cols);
    } catch (e) {
      message.error('获取成绩数据失败');
    } finally {
      setScoreLoading(false);
    }
  };

  // 加载职位数据
  const loadPositions = async (params: any = {}) => {
    setTableLoading(true);
    try {
      const res = await fetchPositions({
        province: params.province,
        city: params.city,
        date: params.date,
        ...params
      });
      setTableData(res.data || []);

      // 动态表头 + filterSearch
      const cols = (res.positionNameKeyMap || []).map((col: any) => {
        const filtersOptions = Array.from(
          new Set((res.data || []).map((item: any) => item[col.key || col]))
        ).map((v: any) => ({ text: v, value: v }));

        return {
          title: col.name || col,
          dataIndex: col.key || col,
          filters: filtersOptions.length > 1 ? filtersOptions : undefined,
          onFilter:
            filtersOptions.length > 1
              ? (value: any, record: any) => record[col.key || col] === value
              : undefined,
          filterSearch: true,
          ...col,
          render: (text: any, record: any) => {
            if ((col.key || col) === 'positionCode') {
              return <a onClick={() => openScoreDialog(record[col.key || col])}>{text}</a>;
            }
            return text;
          },
        };
      });

      setTableColumns(cols);
    } catch (e) {
      message.error('获取职位数据失败');
    } finally {
      setTableLoading(false);
    }
  };

  // 加载文件树
  const loadFileTree = async () => {
    try {
      const res = await fetchFileTree();
      setFileTree(res.data || []);
      // 回显选中的文件，如果 localStorage 有值
      const savedFile = localStorage.getItem(STORAGE_KEY);
      if (savedFile) {
        const parsed = JSON.parse(savedFile);
        setSelectedFile(parsed);
        const [province, date, type, city] = parsed;
        loadPositions({ province, city, date });
      }
      setTimeout(() => setReady(true))
    } catch (e) {
      message.error('获取文件树失败');
    }
  };

  useEffect(() => {
    loadFileTree();
  }, []);

  return (
    <div>
      <ProTable
        rowKey="positionCode"
        columns={tableColumns}
        dataSource={tableData}
        loading={tableLoading}
        virtual
        scroll={{
          x: tableColumns.reduce((sum, col) => sum + (col.width || 120), 0),
          y: window.innerHeight - 290,
        }}
        actionRef={actionRef}
        pagination={false}
        search={{ labelWidth: 'auto' }}
        toolBarRender={() => [
          <Cascader
            key="targetFile"
            options={fileTree}
            placeholder="请选择目标文件"
            style={{ width: 300 }}
            value={selectedFile}
            onChange={(value, selectedOptions) => {
              setSelectedFile(value);
              localStorage.setItem(STORAGE_KEY, JSON.stringify(value)); // 保存选择
              const [province, date, type, city] = value;
              loadPositions({ province, city, date });
            }}
          />,
        ]}
        request={async (params) => {
          if (!ready) {
            return { data: [], success: true };
          }
          if (selectedFile.length) {
            const [province, date, type, city] = selectedFile;
            await loadPositions({ province, city, date, ...params });
          }
          return { data: tableData, success: true };
        }}
      />

      <Modal
        title="进面成绩"
        open={scoreVisible}
        onCancel={() => setScoreVisible(false)}
        footer={null}
        width="90%"
        style={{ top: 30 }}
      >
        <Spin spinning={scoreLoading}>
          <ProTable
            rowKey="id"
            columns={scoreColumns}
            dataSource={scoreData}
            virtual
            scroll={{
              x: scoreColumns.reduce((sum, col) => sum + (col.width || 120), 0),
              y: window.innerHeight - 320,
            }}
            toolbar={{
              settings: () => []
            }}
            pagination={false}
          />
        </Spin>
      </Modal>
    </div>
  );
};

export default PositionPage;
